<template>
  <div class="body" v-if="!initLoading">
    <div
      class="header-box"
      :style="[
        `height:${customH}px`,
        `background:rgba(255,255,255,${headOpcity})`,
      ]"
      :class="headOpcity > 0.7 ? 'border' : ''"
    >
      <div
        class="header-title"
        v-if="headOpcity > 0.3"
        :style="[
          `padding-top:${customB.top}px`,
          `height:${customB.height}px`,
          `opacity:${headOpcity}`,
        ]"
      >
        商品详情
      </div>
      <div
        class="header-custom"
        :style="[
          `margin-top: ${customB.top}px`,
          `height: calc(${customB.height}px - 2rpx)`,
          `border-radius: calc(${customB.height}px - 2rpx)`,
        ]"
      >
        <div
          class="header-custom-after icon icon-zuo-1"
          v-if="backStatus"
          @click="toBack"
          :style="[
            `height:${customB.height}px`,
            `width:${customB.height}px`,
            `line-height:${customB.height}px`,
          ]"
        ></div>
        <div
          class="icon icon-home"
          @click="toHome"
          :style="[
            `height:${customB.height}px`,
            `width:${customB.height}px`,
            `line-height:${customB.height}px`,
            `padding:0 ${backStatus ? 10 : 0}px`,
          ]"
        ></div>
      </div>
    </div>
    <template v-if="!initError">
      <div class="banner-box">
        <swiper
          v-if="bannerType == 'img'"
          autoplay="true"
          interval="5000"
          duration="150"
          circular="true"
          @change="bannerChange"
        >
          <swiper-item
            v-for="(item, index) in goodsDetail?.goods_imgs"
            :key="index"
            :data-imgs="goodsDetail?.goods_imgs"
            :data-index="index"
            @click.stop="previewImage($event)"
          >
            <image :src="item" class="slide-image" mode="" />
          </swiper-item>
        </swiper>
        <div v-if="bannerType == 'img'" class="tag-banner">
          {{ bannerIndex + 1 }}/{{ goodsDetail?.goods_imgs.length || 0 }}
        </div>
      </div>

      <div class="goods-detail">
        <div class="goods-title">
          <div class="goods-price-box">
            <money size="fz-large-x" fw :value="goodsDetail.goods_price"></money>
            <money class="ml5" market :value="goodsDetail.market_price"></money>
            <div
              class="goods-buy-least ml5"
              v-if="goodsDetail.buy_least_status"
            >
              <div>起购</div>
              <div class="ml2">{{ goodsDetail.buy_least }}件</div>
            </div>
            <div class="goods-buy-limit" v-if="goodsDetail.buy_limit_status">
              <div>限购</div>
              <div class="ml2">{{ goodsDetail.buy_limit }}件</div>
            </div>
          </div>
          <div class="goods-title-box">
            <text class="goods-title-text">{{ goodsDetail.goods_name }}</text>
          </div>
          <div
            v-if="goodsDetail.selling_point !== ''"
            class="goods-title-desc fz-small"
            :style="{ color: DIYTHEME?.host_bg }"
          >
            {{ goodsDetail.selling_point }}
          </div>
          <div class="goods-sale-info fz-small">
            <div v-if="goodsDetail.delivery_express == 10">免邮</div>
            <div
              v-if="goodsDetail.sales_actual + goodsDetail.sales_initial > 0"
            >
              销量{{ goodsDetail.sales_actual + goodsDetail.sales_initial }}件
            </div>
          </div>
        </div>
      </div>

      <!-- 商品服务 -->
      <div
        class="goods-cell goods-server"
        v-if="goodsDetail.server.length > 0"
        @click="showServerPopup"
      >
        <div class="cell-title">服务</div>
        <div class="cell-desc">
          <div
            v-for="(item, index) in goodsDetail.server"
            :key="index"
            class="server-item"
          >
            <image class="icon" :src="item.icon" />
            <div class="ml5 fz12">{{ item.server_name }}</div>
          </div>
        </div>
      </div>
      <bottomPopup ref="serverPopupRef" :mask="true" title="商品服务">
        <div class="server-popup-box pl10 pr10">
          <div
            class="server-item"
            v-for="(item, index) in goodsDetail.server"
            :key="index"
          >
            <div class="title">
              <image class="icon" :src="item.icon" />
              <div class="text">{{ item.server_name }}</div>
            </div>
            <div class="desc">
              <div>{{ item.server_desc }}</div>
            </div>
          </div>
        </div>
      </bottomPopup>

      <!-- 商品详细 -->
      <div class="goods-content-box">
        <div class="goods-content-title">商品详细</div>
        <div class="goods-content">
          <div v-if="goodsDetail.content == ''" class="product-content-empty">
            商品无详细
          </div>
          <rich-text
            type="text"
            :data-imgs="goodsDetail.content.img"
            :nodes="goodsDetail.content.html"
          ></rich-text>
        </div>
      </div>

      <div v-if="!initLoading" class="goods-bottom">
        <div class="goods-bottom-left">
          <div class="goods-bottom-left-item" bindtap="openShare">
            <div class="icon icon-fenxiang"></div>
          </div>
          <div class="goods-bottom-left-item" @click="toCollection">
            <div
              class="icon"
              :class="goodsCollectin ? 'icon-like-fill' : 'icon-like'"
              :style="{
                color: goodsCollectin ? DIYTHEME?.host_bg : '',
              }"
            ></div>
          </div>
          <div class="goods-bottom-left-item" @click="toCart">
            <div class="icon icon-gouwu-2"></div>
            <div class="goods-cart-count" v-if="goodsCartCount > 0">
              {{ goodsCartCount }}
            </div>
          </div>
        </div>
        <div class="goods-bottom-right">
          <template v-if="goodsDetail.stock > 0">
            <hover class="hover-btn">
              <div
                class="sku-btn"
                :style="[
                  `background: ${DIYTHEME?.deputy_bg}`,
                  `color: ${DIYTHEME?.host_bg}`,
                ]"
                @click.stop="toSku"
              >
                加入购物车
              </div>
            </hover>
            <hover class="hover-btn">
              <div
                class="sku-btn"
                :style="[
                  `background:linear-gradient(to right,${DIYTHEME?.host_bg2},${DIYTHEME?.host_bg});`,
                  `color: ${DIYTHEME?.host_color}`,
                ]"
                @click.stop="toSku"
              >
                立即购买
              </div>
            </hover>
          </template>
          <div class="empty-stock-btn" v-if="goodsDetail.stock < 1">
            库存不足
          </div>
        </div>
      </div>
    </template>
    <div class="goods-error" v-else>
      {{ initErrorMsg }}
    </div>
    <toTop @change="scrollToTop()" ref="toTopRef"></toTop>
    <goodsSku
      ref="goodsSkuRef"
      @close="skuClose"
      :goodsId="goodsId"
      @init="toInit"
      bottom="0"
    ></goodsSku>
  </div>
  <init-load ref="initLoadRef" v-if="initLoading"></init-load>
</template>
<script lang="ts" setup>
import { ref, getCurrentInstance, nextTick } from "vue";
import { onLoad, onShow, onPageScroll } from "@dcloudio/uni-app";
import { getGoodsDetail } from "@/api/goods";
import { createGoodsCollection } from "@/api/goods-collection";
import { Result, ResultError } from "@/types";
import { configStore, useConfig } from "@/store";
import bottomPopup from "@/components/ui/bottom-popup/index.vue";
import toTop from "@/components/ui/to-top/index.vue";
import goodsSku from "@/components/goods-sku/index.vue";
import { format } from "@/utils/rich";
import { storeToRefs } from "pinia";
const { DIYTHEME } = storeToRefs(useConfig());
const {
  proxy,
  proxy: { $utils },
} = getCurrentInstance() as any;

type goodsIdType = number | string | undefined;

const initLoading = ref<boolean>(true);

const initError = ref<boolean>(false);

const initErrorMsg = ref<string>("");

const goodsId = ref<goodsIdType>(0);

const goodsDetail = ref<any>();

const goodsCartCount = ref<number>(0);

const goodsCollectin = ref<boolean>(false);

const customH = ref<string | number>(0);

const customB = ref<{
  top?: number;
  width?: number;
  height?: number;
}>({
  top: 0,
  width: 0,
  height: 0,
});

const backStatus = ref<boolean>(true);

const headOpcity = ref<string | number>(0);

const scrollH = ref<string | number>(240);

let systemInfo = uni.getSystemInfoSync();

onLoad((query: any) => {
  goodsId.value = query.id ? query.id : 0;
});

onShow(() => {
  nextTick(() => {
    toInitSystem();
    toInit();
  });
});

const toInitSystem = () => {
  let capsule = uni.getMenuButtonBoundingClientRect();
  let statusH = systemInfo.statusBarHeight || 0;
  if (capsule) {
    customH.value = statusH + 44;
  } else {
    customH.value = statusH + 50;
  }
  customB.value = capsule;
  uni.getSystemInfo({
    success: (res) => {
      scrollH.value = res.windowWidth;
    },
  });

  var pages = getCurrentPages();
  if (pages.length == 1) {
    backStatus.value = false;
  }
};

const bannerType = ref<string>("img");

const bannerIndex = ref<number>(0);

const bannerChange = (e: any) => {
  bannerIndex.value = e.detail.current;
};

// 查看大图
const previewImage = (e: any) => {
  let contentimg = e.currentTarget.dataset.imgs,
    index = e.currentTarget.dataset.index || -1;
  uni.previewImage({
    current: index == -1 ? contentimg : contentimg[index],
    urls: contentimg,
  });
};

const toBack = () => {
  uni.navigateBack({
    delta: 0,
  });
};

const toHome = () => {
  $utils.routeRedirectTo("/pages/index/index");
};

const toCollection = () => {
  if ($utils.checkLogin("login")) {
    createGoodsCollection({
      id: goodsId.value,
    })
      .then((res: Result) => {
        goodsCollectin.value = res.data;
      })
      .catch((err: ResultError) => {
        $utils.errorMsg(err);
      });
  }
};

const toCart = () => {
  $utils.routeRedirectTo("/pages/cart/index");
};

const serverPopupRef = ref<HTMLElement>();

const showServerPopup = () => {
  proxy?.$refs["serverPopupRef"]?.open();
};

const toInit = () => {
  if (!goodsId.value) {
    return false;
  }
  getGoodsDetail({
    id: goodsId.value,
  })
    .then((res: Result) => {
      initLoading.value = false;
      initError.value = false;
      goodsDetail.value = res.data.goods;
      goodsCartCount.value = res.data.goods_cart_count;
      goodsCollectin.value = res.data.goods_collectin;

      // 富文本转码
      if (goodsDetail.value.content.length > 0) {
        goodsDetail.value.content = format(goodsDetail.value.content);
      }
    })
    .catch((err: ResultError) => {
      initLoading.value = false;
      initError.value = true;
      initErrorMsg.value = err?.data?.message || err.message || "未知错误";
      $utils.errorMsg(err);
    });
};

const goodsSkuRef = ref<HTMLElement>();

const toSku = () => {
  if ($utils.checkLogin("login")) {
    proxy?.$refs["goodsSkuRef"]?.open();
  }
};
const skuClose = () => {
  proxy?.$refs["goodsSkuRef"]?.close();
};

const toTopRef = ref<HTMLElement>();

//页面滚动执行方式
onPageScroll((e) => {
  proxy?.$refs["toTopRef"]?.scroll(e);
  let scroll = e.scrollTop <= 0 ? 0 : e.scrollTop;
  let opcity = scroll / Number(scrollH.value);
  if (headOpcity.value >= 1 && opcity >= 1) {
    return;
  }
  headOpcity.value = opcity;
});

const scrollToTop = () => {
  uni.pageScrollTo({
    duration: 200,
    scrollTop: 0,
  });
};
</script>



<style>
page {
  background: var(--base-page);
}
</style>
<style scoped>
.body {
  padding-bottom: 150rpx;
}

.header-box {
  width: 100%;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 99;
}
.header-box.border {
  border-bottom: 1rpx solid #f0f0f0;
}

.header-title {
  width: 100%;
  font-size: var(--base-size-default);
  line-height: 36rpx;
  font-weight: 500;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #000000;
}

.header-custom {
  position: fixed;
  left: 20rpx;
  top: 0;
  display: flex;
  align-items: center;
  height: 60rpx;
  transform: translateZ(0);
  z-index: 99;
  background: rgba(182, 182, 182, 0.5);
  border: 1rpx solid rgba(166, 166, 166, 0.5);
}

.icon-ml {
  margin-left: 20rpx;
}

.header-custom .icon {
  height: 60rpx;
  width: 60rpx;
  display: block !important;
  text-align: center;
  line-height: 60rpx;
  color: #000000;
  font-size: var(--base-size-large);
  position: relative;
  padding: 0 10rpx;
}
.header-custom .header-custom-after:after {
  position: absolute;
  content: "";
  height: 24rpx;
  width: 1rpx;
  background: rgba(166, 166, 166, 0.5);
  right: -0.5rpx;
  top: calc(50% - 12rpx);
}

.banner-box {
  position: relative;
  height: 700rpx;
}

.banner-box swiper,
.banner-box .slide-image {
  width: 100%;
  display: block;
  height: 700rpx;
}

.tag-banner {
  position: absolute;
  color: #fff;
  height: 32rpx;
  bottom: 30rpx;
  line-height: 32rpx;
  right: 0;
  padding: 0 12rpx;
  font-size: var(--base-size-small-xx);
  border-top-left-radius: 6rpx;
  border-bottom-left-radius: 6rpx;
  background: rgba(0, 0, 0, 0.5);
}

.banner-box .bottom-box {
  position: absolute;
  bottom: 70rpx;
  width: 100%;
  display: flex;
  justify-content: center;
}

.banner-box .bottom-box .item {
  padding: 0 20rpx;
  margin: 0 10rpx;
  height: 40rpx;
  line-height: 40rpx;
  border-radius: 40rpx;
  font-size: var(--base-size-small);
  background: #fff;
}

.goods-detail {
  box-sizing: border-box;
}

.goods-title {
  background: #fff;
  padding: 30rpx 20rpx;
}

.goods-price-box {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  line-height: 50rpx;
}

.goods-detail .goods-price {
  font-size: var(--base-size-large-xx);
}

.goods-title-box {
  margin-top: 20rpx;
  margin-bottom: 10rpx;
  /* font-weight: bold; */
  line-height: 50rpx;
  font-size: var(--base-size-large-x);
}
.goods-title-desc {
  padding: 20rpx 0;
}
.goods-sale-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-top: 20rpx;
  color: #777777;
  position: relative;
}
.goods-error {
  position: fixed;
  top: 40%;
  width: 100%;
  text-align: center;
  color: var(--base-grey);
}

.goods-cell {
  margin-top: 20rpx;
  background: #fff;
  display: flex;
  white-space: nowrap;
  padding: 30rpx;
  width: calc(100% - 60rpx);
}

.cell-title {
  width: 80rpx;
}

.cell-text {
  width: calc(100% - 280rpx);
  margin-left: 20rpx;
  white-space: nowrap;
}

.cell-desc {
  width: 200rpx;
  text-align: right;
}

.goods-server .cell-desc {
  width: calc(100% - 100rpx);
  display: flex;
  justify-content: flex-start;
  overflow: hidden;
}

.goods-server .cell-desc .server-item {
  margin-right: 20rpx;
  white-space: nowrap;
  display: flex;
  align-items: center;
}

.goods-server .cell-desc .server-item .icon {
  height: 30rpx;
  width: 30rpx;
}

.server-popup-title {
  line-height: 80rpx;
  text-align: center;
}

.server-popup-box .server-item {
  margin-bottom: 20rpx;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f9f9f9;
}

.server-popup-box .server-item .title {
  height: 50rpx;
  display: flex;
  align-items: center;
}

.server-popup-box .server-item .title .icon {
  margin-right: 20rpx;
  height: 30rpx;
  width: 30rpx;
}

.server-popup-box .server-item .desc {
  color: #999999;
}

.goods-content-title {
  text-align: center;
  line-height: 80rpx;
  position: relative;
  width: 100%;
  margin: 0 auto;
  font-weight: bold;
}

.goods-content-box {
  margin-top: 20rpx;
  background: #ffffff;
}

.goods-content {
  width: 100%;
  border-top: 1rpx solid #f5f5f5;
}

.goods-bottom {
  position: fixed;
  width: calc(100% - 40rpx);
  background: #fff;
  height: 80rpx;
  bottom: 0;
  padding: 20rpx;
  left: 0;
  display: flex;
  z-index: 999;
  justify-content: space-between;
  border-top: 1rpx solid #f5f5f5;
}

.goods-bottom-left {
  display: flex;
  width: 35%;
  justify-content: space-around;
}

.goods-bottom-left-item {
  text-align: center;
  position: relative;
  padding: 5rpx 0;
  line-height: 70rpx;
  width: 100rpx;
}

.goods-bottom-left-item .icon {
  font-size: var(--base-size-large-xx);
  color: #333333;
}

.goods-cart-count {
  top: 10rpx;
  right: 10rpx;
}

.goods-bottom-right {
  display: flex;
  width: 60%;
  justify-content: space-between;
  font-size: var(--base-size-default);
  align-items: center;
}

.goods-bottom-right .hover-btn {
  width: calc(50% - 10rpx);
  margin: 5rpx 0;
}
.goods-bottom-right .sku-btn {
  text-align: center;
  line-height: 70rpx;
  border-radius: var(--base-radius-small);
}
.go-buy {
  color: #fff;
}
</style>